// 连接 WebSocket
function connectWebSocket() {
  websocket = new WebSocket(
    `${import.meta.env.VITE_WS_TYPE}://${
      import.meta.env.VITE_DEVELOPMENT_URL
    }/api/ws/asr`
  );
  websocket.onopen = () => {
    console.log("WebSocket 连接成功");
    updateStatus("connected", "已连接到服务器");
  };

  websocket.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.type === "result" && data.text) {
      // 追加识别结果
      resultDiv.textContent += data.text;
      // 自动滚动到底部
      resultDiv.parentElement.scrollTop = resultDiv.parentElement.scrollHeight;
    } else if (data.type === "error") {
      showError("识别错误: " + data.error);
    }
  };

  websocket.onerror = (error) => {
    console.error("WebSocket 错误:", error);
    showError("WebSocket 连接错误");
    updateStatus("disconnected", "连接错误");
  };

  websocket.onclose = () => {
    console.log("WebSocket 连接关闭");
    updateStatus("disconnected", "连接已断开");
    if (isRecording) {
      stopRecording();
    }
  };
}

// 开始录音
async function startRecording() {
  try {
    // 清空之前的结果
    resultDiv.textContent = "";

    // 连接 WebSocket
    if (!websocket || websocket.readyState !== WebSocket.OPEN) {
      connectWebSocket();
      // 等待连接建立
      await new Promise((resolve, reject) => {
        const timeout = setTimeout(() => reject(new Error("连接超时")), 5000);
        const checkConnection = setInterval(() => {
          if (websocket.readyState === WebSocket.OPEN) {
            clearInterval(checkConnection);
            clearTimeout(timeout);
            resolve();
          }
        }, 100);
      });
    }

    // 获取麦克风权限
    mediaStream = await navigator.mediaDevices.getUserMedia({
      audio: {
        sampleRate: 16000,
        channelCount: 1,
        echoCancellation: true,
        noiseSuppression: true,
      },
    });

    // 创建音频上下文
    audioContext = new (window.AudioContext || window.webkitAudioContext)({
      sampleRate: 16000,
    });

    source = audioContext.createMediaStreamSource(mediaStream);

    // 创建处理器节点（使用旧版 API 以获得更好的兼容性）
    // 缓冲区大小必须是 2 的幂次方，使用 8192 (约 512ms at 16kHz)
    processor = audioContext.createScriptProcessor(8192, 1, 1);

    processor.onaudioprocess = (e) => {
      if (!isRecording) return;

      const inputData = e.inputBuffer.getChannelData(0);

      // 发送音频数据到服务器
      if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(inputData.buffer);
      }

      // 可视化
      visualize(inputData);
    };

    source.connect(processor);
    processor.connect(audioContext.destination);

    isRecording = true;
    updateStatus("recording", "正在录音中...");
    startBtn.disabled = true;
    stopBtn.disabled = false;
  } catch (error) {
    console.error("录音错误:", error);
    showError("无法访问麦克风: " + error.message);
  }
}

// 停止录音
function stopRecording() {
  isRecording = false;

  if (processor) {
    processor.disconnect();
    processor = null;
  }

  if (source) {
    source.disconnect();
    source = null;
  }

  if (mediaStream) {
    mediaStream.getTracks().forEach((track) => track.stop());
    mediaStream = null;
  }

  if (audioContext) {
    audioContext.close();
    audioContext = null;
  }

  updateStatus("connected", "已停止录音");
  startBtn.disabled = false;
  stopBtn.disabled = true;
}
